package com.hebeu.group.controller;

import com.hebeu.group.pojo.User;
import com.hebeu.group.service.UserService;
import com.hebeu.group.util.JSONResult;
import com.hebeu.group.util.QcloudSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 言立慧
 * @date 2018/8/12 10:29
 */

@Controller
@RequestMapping("/user")
public class RegisterController {
    private final static Pattern PHONE_PATTERN = Pattern.compile("1\\d{10}");
    private final static int VERIFICATION_CODE_LENGTH = 6;
    private final static int OK_STATUS = 200;

    private UserService usersService;

    @Autowired
    public RegisterController(UserService usersService) {
        this.usersService = usersService;
    }


    /**
     * 修改密码,一般登录情况下
     *
     * @param users
     * @return
     */
    @RequestMapping("/changePassword")
    @ResponseBody
    public JSONResult changePassword(User users, String oldPassword) {
        return JSONResult.ok("更新成功");
    }


    /**
     * 验证码发送:注册时使用
     *
     * @return
     */
    @RequestMapping("/postVerificationCode")
    @ResponseBody
    public JSONResult postVerificationCode(String phoneNumber, HttpSession session) {
        StringBuffer stringBuffer;
        System.out.println("=============>" + phoneNumber);
        if (phoneNumber == null) {
            return JSONResult.errorMsg("电话号码不能为空");
        } else {
            //调用正则表达式分析
            Matcher m = PHONE_PATTERN.matcher(phoneNumber);
            if (!m.matches()) {
                return JSONResult.errorMsg("您输入的电话号码不合法！");
            } else {
                //判断是否已经存在了此手机号
                if (!usersService.isExist(phoneNumber)) {
                    //生成6位随机验证码
                    stringBuffer = new StringBuffer();
                    Random random = new Random();
                    for (int i = 0; i < VERIFICATION_CODE_LENGTH; i++) {
                        stringBuffer.append(random.nextInt(10));
                    }
                    //发送验证码
                    JSONResult x = postCode(phoneNumber, session, stringBuffer);
                    if (x != null) {
                        return x;
                    }
                } else {
                    return JSONResult.errorMsg("此手机号已经注册！");
                }
            }
        }

        return JSONResult.ok(stringBuffer.toString());
    }

    /**
     * 验证码校验
     *
     * @param session
     * @param verCode
     * @return
     */
    @RequestMapping("/sureVerificationCode")
    @ResponseBody
    public JSONResult sureVerificationCode(HttpSession session, String verCode) {
        Long tenMinute = Long.valueOf(10 * 60 * 1000);
        //1.确认验证码输入是否正确
        Long postTime = (Long) session.getAttribute("postTime");
        String code = (String) session.getAttribute("code");
        if ((System.currentTimeMillis() - postTime) >= tenMinute) {
            return JSONResult.errorMsg("验证码已经失效");
        }
        if (!code.equals(verCode)) {
            return JSONResult.errorMsg("验证码输入错误");
        }
        return JSONResult.ok("验证码输入正确");
    }

    /**
     * 通过手机验证码修改密码
     *
     * @param phone
     * @param newPassword
     * @return
     */
    @RequestMapping("/changePasswordByCode")
    @ResponseBody
    public JSONResult passwordChange(String code, String phone, String newPassword, HttpSession session) {
        return JSONResult.ok();
    }

    /**
     * 找回密码
     *
     * @param phone
     * @param newPassword
     * @return
     */
    @RequestMapping("/findPassword")
    @ResponseBody
    public JSONResult findPassword(String phone, String newPassword) {
        return JSONResult.ok("修改密码成功");
    }


    /**
     * 验证码的发送
     *
     * @param phoneNumber
     * @param session
     * @param stringBuffer
     * @return
     */
    public JSONResult postCode(String phoneNumber, HttpSession session, StringBuffer stringBuffer) {
        try {
            if (!QcloudSms.sendCode(phoneNumber, stringBuffer.toString())) {
                return JSONResult.errorMsg("验证码发送失败");
            } else {
                //将验证码保存到session中
                session.setAttribute("code", stringBuffer.toString());
                System.out.println(stringBuffer.toString());
                session.setAttribute("postTime", System.currentTimeMillis());
            }
        } catch (Exception e) {
            return JSONResult.errorException("服务器异常");
        }
        return JSONResult.ok();
    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @RequestMapping
    @ResponseBody
    public JSONResult register(User user) {
        //1. 设置user
        usersService.insertUser(user);
        //2. 返回数据
        return JSONResult.ok(user);
    }

}
